package com.xln.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xln.dao.ArticleMapper;
import com.xln.pojo.Article;
import com.xln.pojo.Tag;
import com.xln.service.ArticleService;
import com.xln.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Resource
    private TagService tagService;

    @Transactional
    @Override
    public boolean saveArticle(Article article) {

        updateTag(article);

        return this.save(article);
    }

    @Transactional
    @Override
    public boolean updateArticle(Article article) {

        updateTag(article);
        return this.updateById(article);
    }

//    创建或更新标签
    private void updateTag(Article article) {
        String[] tags = article.getTags().split(",");
        log.info("文章标签：{}", tags);
        // 获取所有已存在的标签
        List<Tag> allTag = tagService.list();

        Tag tag = new Tag();
        ArrayList<Tag> newTags = new ArrayList<>();
        List<Long> oldTagsId = new ArrayList<>();
        int flag = 0;
        for (String tagName : tags) {
            for (Tag tagOld : allTag){
                // 检查标签是否已存在
                if (tagName.equals(tagOld.getName())){
                    //存在
                    flag = 1;
                    oldTagsId.add(tagOld.getId());
                    break;
                }
            }
//            不存在
            if (flag == 0){
                tag.setName(tagName);
                tag.setArticleCount(1);
                newTags.add(tag);
            }
        }
// 如果标签不存在，创建新标签
        if (!newTags.isEmpty()) {
            boolean newResult = tagService.saveBatch(newTags);
        }
        // 如果标签已存在，更新标签文章数量
        if (!oldTagsId.isEmpty()){
            boolean oldResult = tagService.update(Wrappers.<Tag>lambdaUpdate()
                    .in(Tag::getId, oldTagsId)
                    .setSql("article_count = article_count + 1"));
        }
    }


}
